package com.es.exception;

import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.indices.InvalidIndexNameException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ExceptionAdive
 * @author: maliang
 * @Description 异常集中处理
 * @date 2021/12/1 9:17
 * @Version 1.0版本
 */
@ControllerAdvice
public class ExceptionAdvive {

    @ResponseBody
    @ExceptionHandler(value = EsException.class)
    public Map<String, Object> esException(EsException ex) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("code", 400);
        map.put("msg", ex.getMessage());
        return map;
    }

    @ResponseBody
    @ExceptionHandler(value = InvalidIndexNameException.class)
    public Map<String, Object> invalidIndexNameException(InvalidIndexNameException ex) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("code", 400);
        map.put("msg", "无效的索引名称异常");
        return map;
    }

    @ResponseBody
    @ExceptionHandler(value = ElasticsearchStatusException.class)
    public Map<String, Object> elasticsearchStatusException(ElasticsearchStatusException ex) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("code", 400);
        map.put("msg", "Elasticsearch 状态异常");
        return map;
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> error(Exception ex) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("code", 500);
        map.put("msg", "未知错误");
        return map;
    }

    @ResponseBody
    @ExceptionHandler(value = IndexNotFoundException.class)
    public Map<String, Object> indexNotFoundException(IndexNotFoundException ex) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("code", 400);
        map.put("msg", "未找到索引异常");
        return map;
    }

}
